<template>
  <div class="main flex h-screen">
    <div class="w-full flex items-center justify-center p-8">
      <div class="w-full bg-white is-always-shadow" style="width: 600px">
        <div class="flex">
          <div class="main text-left text-white" style="width:45%; height: 50vh;">
            <div class="pt-16 px-8" style="width:100%; height: 100%;background-color: rgba(54,63,97,0.7);">
              <h3 class="text-xl font-bold">{{ tenantInfo.systemName }}</h3>
              <div class="pt-2">{{ tenantInfo.remark }}</div>

            </div>
          </div>
          <div class="pt-16 px-8" style="width:55%; height: 50vh">
            <!--            <h3 class="text-xl font-bold text-left">请登录</h3>-->
            <el-menu default-active="1" mode="horizontal">
              <el-menu-item index="1">登录</el-menu-item>
            </el-menu>
            <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" class="pt-2 space-y-4" size="large">
              <el-form-item prop="username">
                <el-input v-model="loginForm.username"
                          placeholder="请输入用户名"
                          prefix-icon="search"
                          clearable
                          @keyup.enter.native="submitForm"/>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="loginForm.password"
                          type="password"
                          show-password
                          prefix-icon="lock"
                          placeholder="请输入密码"
                          @keyup.enter.native="submitForm"/>
              </el-form-item>
              <el-form-item v-if="captchaEnabled" prop="captcha">
                <el-input v-model="loginForm.captcha" placeholder="请输入验证码" style="width: 176px;"></el-input>
                <img :src="captchaUrl"
                     alt="验证码"
                     @click="refreshCaptcha"
                     style="cursor: pointer; margin-left: 10px; height:40px;">
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-button v-loading="loading" type="primary" class="w-full" @click="submitForm">登录</el-button>
              </el-form-item>
            </el-form>

          </div>
        </div>
        <!--        <div class="text-center mb-6">-->
        <!--          <img src="/logo.png" alt="Logo" class="w-20 mx-auto mb-2" />-->
        <!--          <h2 class="text-xl font-bold">欢迎登录</h2>-->
        <!--        </div>-->


      </div>
    </div>
    <div class="bottom-4 left-0 right-0 absolute text-white">©Copyright 2025 成都高新区一点繁星软件工作室</div>
  </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref, reactive} from 'vue'
import $message from '@/utils/message.js';
import $gm4 from '@/utils/gm-sm4.js';
import $apiService from '@/axios/api.js';
import {useRouter} from 'vue-router';
import {isPasswordExpired} from "@/utils/misc.js";
import {$localStorage} from "@/utils/application-storage.js";

const $router = useRouter();
const tenantCode = $localStorage.getTenantCode()
let loading = ref(false)
let captchaEnabled = ref(false)
let captchaUrl = ref('')
const loginForm = ref({
  username: '',
  password: '',
  captcha: '',
  s: new Date().getTime(),
  remember: false,
})
let tenantInfo = ref({
  logo: "",
  remark: "",
  systemName: "",
})
const loginFormRef = ref(null);
const loginFormRules = reactive({
  username: [{required: true, message: '请输入账户', trigger: 'blur'}],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}],
})

onMounted(() => {
  queryMyByCode()
});
onUnmounted(() => {
});

const queryMyByCode = () => {
  if (!tenantCode) return $message.error('请先确定登录租户Code')
  refreshCaptcha()
  $apiService.handshake().then((res) => {
    captchaEnabled.value = res.data.endsWith('captcha')

    let enc = 'N'
    if (res.data.startsWith('encfi')) enc = 'F'
    if (res.data.startsWith('encfdy')) enc = 'D'
    // 将信息缓存到本地
    $localStorage.setENC(enc)

    const params = {params: {tenantCode: tenantCode}}
    $apiService.tenantViewQueryMyByCode(params).then((res) => {
      const {id, info, nickname} = res.data.data
      $localStorage.setTenantInfo({id, ...info, nickname, tenantCode})
      tenantInfo.value = info
      // 动态更新element主题
      // this.setSystemTheme(res.data.data)
    })
  })
}
const refreshCaptcha = () => {
  const now = new Date().getTime()
  loginForm.value.s = now
  captchaUrl.value = `${import.meta.env.VITE_API_BASE_URL}/${tenantCode}/api/epms/oauth/token.captcha?s=${now}`
}

// toChangePassword(forceModifyCredentialTime) {
//   if (new Date(forceModifyCredentialTime).valueOf() - new Date().valueOf() < 0) {
//     this.$message.warning('您的账号密码已过期，请更改密码')
//     this.$router.push(`/${this.tenantCode}/password`)
//     return true
//   } else if (new Date(forceModifyCredentialTime).valueOf() - new Date().valueOf() < 864000000) {
//     this.$message.warning('您的账号距离密码过期已不足10天，请及时更改密码')
//     return false
//   } else {
//     return false
//   }
// }
// 提示是否需要修改密码


const submitForm = () => {
  if (!loginFormRef) return
  const formEl = loginFormRef.value;
  formEl.validate((valid) => {
    if (!valid) return

    // 准备参数
    loading = true
    const param = {
      username: loginForm.value.username,
      credential: $gm4.encrypt(loginForm.value.password),
      grantType: 'credential',
      captcha: loginForm.value.captcha,
      s: loginForm.value.s,
    }
    $apiService.login(param).then((res) => {
      if (res.data.access_token && res.data.sourceType === 'Outer') {
        // 先判断密码是否过期
        const passwdValidity = isPasswordExpired(res.data.forceModifyCredentialTime)
        if (passwdValidity === 'Expired') {
          $message.error('您的账号密码已过期，请修改')
          // $router.push(`/${this.tenantCode}/password`)
        }
        if (passwdValidity === 'ExpiredIn30Days') {
          $message.warning('您的账号密码即将过期，请及时修改')
        }
        if (res.data.modifyCredentialStatus.toLowerCase() !== 'yes') { // 判断是否修改过密码, 首次登录需要修改密码
          $router.push({name: 'ChangePassword'});
          return
        }

        $localStorage.setToken(res.data.access_token)

        // 请求当前租户信息
        getMyUserInfo() // 请求当前租户信息

        // 获取菜单配置
        // this.getMyMenuConfig()
      } else {
        $message.error('登录失败！')
      }
    }).catch(e => {
      console.log(e)
      $message.error(e.response.data.message)
    }).finally(() => {
      loading = false
    })
  })
}

// 登录成功后，获取我的信息，并保存vuex
const getMyUserInfo = (param) => {
  $apiService.getPersonalInfo(param).then((res) => {
    $localStorage.setMyProfile(res.data.data)
    // this.$store.dispatch('user/SET_USER_INFO', res.data.data)
    // 首次登录参数
    // if (res.data.data.modifyCredentialStatus === 'No') {
    //   this.$router.push(`/${this.tenantCode}/password`)
    // } else {
    // 跳转
    getMyMenuConfig()
    // }
  })
}

// 登录成功后，获取我的信息，并保存vuex
const getMyMenuConfig = () => {
  $apiService.getMyMenuConfig().then((res) => {

    const menu = {}
    res.data.data.content.forEach((item, index) => {
      if (item.code) {
        menu[item.code] = item.name
      }
    })
    console.log(menu)
    $router.replace({name: 'DashboardWorkSpace'})
    // localStorage.setItem("E-o-my-profile", JSON.stringify(res.data.data))
    // this.$store.dispatch('user/SET_USER_INFO', res.data.data)
    // 首次登录参数
    // if (res.data.data.modifyCredentialStatus === 'No') {
    //   this.$router.push(`/${this.tenantCode}/password`)
    // } else {
    // 跳转
    // this.getMyMenuConfig()
    // }
  })
}

</script>

<style scoped>
.main {
  /*background-image: url("@/assets/images/login-bg.jpeg");*/
  background-image: url("/login-bg.jpg");
  background-size: cover;
}

.is-always-shadow {
  box-shadow: var(--el-box-shadow-light);
}

.el-menu--horizontal {
  --el-menu-horizontal-height: 30px;
}

/* 可选的样式增强 */
</style>
